package com.mvp.mvpdemo

import android.content.Context
import com.google.gson.Gson
import com.mvp.mvpdemo.net.APIService
import com.retrofit.retrofitutil.OkHttpLogInterceptor
import com.retrofit.retrofitutil.RetrofitBuilder
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.*


/**
 * Created By Mahongyin
 * Date    2020/10/19 12:32
 *
 */
class RetrofitTest(val context: Context) {
    private var extraTestParamMap: Map<String, String>
    private var apiService: APIService
    private var mContext: Context = context

    init {
        mContext = context
        extraTestParamMap = mapOf("version" to "888", "author" to "android")
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }
        val retrofit = RetrofitBuilder.instance
            .addInterceptor(OkHttpLogInterceptor())
            .baseUrl(Const.BASE_URL)
            .addParams(extraTestParamMap)
            .addConverterFactory(GsonConverterFactory.create())
            .build(context)
        apiService = retrofit.create(APIService::class.java)
    }


    fun upload(user: String, token: String, fileMap: TreeMap<String, File>) {
        val fileList = createMultipartBodyPartList(fileMap)
        var paparm=TreeMap<String, RequestBody>()
        val userBody=RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), user)
        val tokenBody=RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), token)
        paparm["user"] = userBody
        paparm["token"] =tokenBody
        val uploadFile = apiService.uploads(paparm, fileList)
        uploadFile.enqueue(object : Callback<ResponseBody> {
                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                    if (call.isCanceled) {
                        // cancel

                    } else {
                        // fail

                    }
                }

                override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                    if (response.isSuccessful && response.body() != null) {
                        // success

                    }
                }
            })
    }
fun createMultipartBodyPartList(fileMap: Map<String, File>): List<MultipartBody.Part> {
    val partList = arrayListOf<MultipartBody.Part>()
    for (key in fileMap.keys) {
        val file = fileMap[key]
        file?.apply {
                val requestBody = RequestBody.create(MediaType.parse("image/*"),this)
                val part = MultipartBody.Part.createFormData(key, this.name, requestBody)
                partList.add(part)
        }
    }
    return partList
}

    /**
     * @param bean= entity 或 map
     *   val paramsMap = HashMap<String, String>();
            paramsMap.put("userId", "173000000");
     */
    private fun postJson(bean: Any) {
        val gson = Gson()
        val strEntity = gson.toJson(bean);
        val body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity)

        val call = apiService.postJson(body);
        call.enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                if (call.isCanceled) {
                    // cancel

                } else {
                    // fail

                }
            }

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful && response.body() != null) {
                    // success

                }
            }
        })
    }
}